package com.kanshu.ksgb.fastread.doudou.common.business.ad

import android.app.Activity
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.ak.torch.shell.nati.TorchNativeAdLoader
import com.hz.yl.b.mian.CenBanner
import com.inmobi.ads.InMobiNative
import com.kanshu.ksgb.fastread.doudou.app.Xutils
import com.kanshu.ksgb.fastread.doudou.common.business.ad.presenter.AdPresenter
import com.kanshu.ksgb.fastread.doudou.common.business.ad.retrofit.ADConfigBean
import com.kanshu.ksgb.fastread.doudou.common.business.ad.retrofit.ADConfigs
import com.kanshu.ksgb.fastread.doudou.common.business.ad.toutiao.AdTouTiaoUtils
import com.kanshu.ksgb.fastread.doudou.common.business.ad.utils.AdExploreTimeUtils
import com.kanshu.ksgb.fastread.doudou.common.util.Utils
import com.qq.e.ads.banner.BannerView
import com.qq.e.ads.nativ.NativeExpressADView


/**
 * Title:AdUtils
 * Description: 获取广告工具类
 * Copyright: Copyright(c)2018
 * Company: 看书网
 * CreateTime: 2018/5/16 16:46
 *
 * @author EvanHe
 * @version 3.0
 */
class AdUtils {

    companion object {
        private fun getAdData(activity: Activity, adContainer: ViewGroup?, skipContainer: TextView?, config: ADConfigBean, adStyle: Int, layout: Int, adListener: BaseAdListener?): Boolean {
            //设置不能重复调用
            if (!TextUtils.equals(config.ad_type, ADConfigBean.TYPE_GDT.toString())) {
                pVUVAd(AdPresenter.AD_REQUEST, config)
            }
            when (config.ad_type.toInt()) {
                ADConfigBean.TYPE_OWN, ADConfigBean.TYPE_LUOMI -> {
                }
                else ->
                    if (TextUtils.isEmpty(config.ad_position_id)) {
                        return if (TextUtils.isEmpty(config.second_ad_position_id)) {
                            adListener?.onAdLoadFailed()
                            false
                        } else {
                            if (adStyle != AdStyleBean.SPLASH_STYLE) {
                                AdUtils.fetchAdFailed(activity, adContainer, config, adStyle, layout, adListener)
                                true
                            } else {
                                adListener?.onAdLoadFailed()
                                false
                            }
                        }
                    }
            }
            Log.i("evan", "=====调用广告===== 广告类型： ${config.ad_type}  广告商：${ADConfigBean.getAdName(config.ad_type)}  广告位置：${config.ad_position}  广告Id：${config.ad_position_id}")
            when (config.ad_type.toInt()) {
                ADConfigBean.TYPE_OWN -> {
                    OwnAdUtils.fetchSplashAd(activity, adContainer, config, skipContainer, adStyle, layout, adListener)
                }
                ADConfigBean.TYPE_GDT -> {
                    if (adStyle != AdStyleBean.BANNER_STYLE) {
                        pVUVAd(AdPresenter.AD_REQUEST, config)
                    }
                    when (adStyle) {
                        AdStyleBean.SPLASH_STYLE -> GdtAdUtils.fetchSplashAd(activity, adContainer, skipContainer, config, adListener)
                        AdStyleBean.BANNER_STYLE -> GdtAdUtils.fetchBannerAd(activity, adContainer, config, adListener)
                        AdStyleBean.BOOK_COVER_STYLE -> GdtAdUtils.fetchNativeAd(activity, adContainer, config, adStyle, layout, adListener, 1)
                        AdStyleBean.IMAGE_TEXT_STYLE -> GdtAdUtils.fetchNativeAd(activity, adContainer, config, adStyle, layout, adListener, 1)
                        else -> adListener?.onAdLoadFailed()
                    }
                }
                ADConfigBean.TYPE_360 -> {
                    Xutils.initAd(ADConfigBean.TYPE_360)
                    Ad360Utils.fetchAd(activity, adContainer, config, adStyle, layout, adListener)
                }
                ADConfigBean.TYPE_INMOBI -> {
                    Xutils.initAd(ADConfigBean.TYPE_INMOBI)
                    when (adStyle) {
                        AdStyleBean.SPLASH_STYLE -> InmobiAdUtils.fetchAd(activity, adContainer, skipContainer, config, adStyle, layout, adListener)
                        AdStyleBean.BANNER_STYLE -> InmobiAdUtils.fetchAd(activity, adContainer, null, config, adStyle, layout, adListener)
                        AdStyleBean.BOOK_COVER_STYLE -> InmobiAdUtils.fetchAd(activity, adContainer, null, config, adStyle, layout, adListener)
                        AdStyleBean.IMAGE_TEXT_STYLE -> InmobiAdUtils.fetchAd(activity, adContainer, null, config, adStyle, layout, adListener)
                        AdStyleBean.REWARDED_REWARDED_VIDEO_STYLE, AdStyleBean.REWARDED_FULL_SCREEN_VIDEO_STYLE
                        -> InmobiAdUtils.fetchRewardedVideoAd(activity, adContainer, config, adListener)
                    }
                }
                ADConfigBean.TYPE_TODAYNEWS -> {
                    Xutils.initAd(ADConfigBean.TYPE_TODAYNEWS)
                    when (adStyle) {
                        AdStyleBean.SPLASH_STYLE -> AdTouTiaoUtils.fetchSplashAd(activity, adContainer, skipContainer, config, adListener)
                    //AdStyleBean.BANNER_STYLE -> AdTouTiaoUtils.fetchBannerAd(activity, adContainer, config, adStyle, layout, adListener)
                        AdStyleBean.BANNER_STYLE -> AdTouTiaoUtils.fetchNativeBannerAd(activity, adContainer, config, adStyle, layout, adListener)
                        AdStyleBean.IMAGE_TEXT_STYLE -> AdTouTiaoUtils.fetchFeedAd(activity, adContainer, config, adStyle, layout, adListener)
                        AdStyleBean.REWARDED_REWARDED_VIDEO_STYLE -> AdTouTiaoUtils.fetchRewardedVideoAd(activity, adContainer, config, adListener)
                        AdStyleBean.REWARDED_FULL_SCREEN_VIDEO_STYLE -> AdTouTiaoUtils.fetchFullScreenVideoAd(activity, adContainer, config, adListener)
                    }
                }
                ADConfigBean.TYPE_LUOMI -> {
                    //Xutils.initAd(ADConfigBean.TYPE_LUOMI)
                    when (adStyle) {
                        AdStyleBean.SPLASH_STYLE -> LuoMiUtils.fetchSplashAd(activity, adContainer, skipContainer, config, adListener)
                        AdStyleBean.BOOK_COVER_STYLE -> LuoMiUtils.fetchNativeAd(activity, adContainer, config, adStyle, layout, adListener)
                        AdStyleBean.BANNER_STYLE -> LuoMiUtils.fetchBannerAd(activity, adContainer, config, adStyle, layout, adListener)
                        AdStyleBean.IMAGE_TEXT_STYLE -> LuoMiUtils.fetchBigBannerAd(activity, adContainer, config, adStyle, layout, adListener)
                    }
                }
                else -> adListener?.onAdLoadFailed()
            }
            return true
        }

        fun fetchRenderAd(activity: Activity, adContainer: ViewGroup?, adConfig: ADConfigBean, adStyle: Int, layout: Int, adListener: BaseAdListener?) {
            //判断保底广告的位置是否为广电通广告
            val positionId = when {
                TextUtils.equals(adConfig.second_ad_type, ADConfigBean.TYPE_GDT.toString()) -> adConfig.second_ad_position_id
                TextUtils.equals(adConfig.third_ad_type, ADConfigBean.TYPE_GDT.toString()) -> adConfig.third_ad_position_id
                else -> ""
            }
            if (TextUtils.isEmpty(positionId)) {
                adListener?.onAdLoadFailed()
                return
            }
            adConfig.ad_position_id = positionId
            adConfig.ad_type = ADConfigBean.TYPE_GDT.toString()
            //调用广告时统计
            if (adStyle != AdStyleBean.BANNER_STYLE) {
                Log.i("pVUVAd", "请求方式：${AdPresenter.AD_REQUEST}  广告商：保底广告-广点通  广告位置：${adConfig.ad_position}  广告Id：$positionId")
                AdPresenter.pVUVAdStatics(AdPresenter.AD_REQUEST, adConfig.ad_type, adConfig.ad_position.toInt())
            }
            when (adStyle) {
            //AdStyleBean.SPLASH_STYLE -> GdtAdUtils.fetchSplashAd(activity, adContainer, skipContainer, adConfig, adListener)
                AdStyleBean.BANNER_STYLE -> GdtAdUtils.fetchBannerAd(activity, adContainer, adConfig, adListener)
                AdStyleBean.BOOK_COVER_STYLE -> GdtAdUtils.fetchNativeAd(activity, adContainer, adConfig, adStyle, layout, adListener, 1)
                AdStyleBean.IMAGE_TEXT_STYLE -> GdtAdUtils.fetchNativeAd(activity, adContainer, adConfig, adStyle, layout, adListener, 1)
                else -> adListener?.onAdLoadFailed()
            }
        }

        //保底广告-头条
        private fun fetchRenderAdByTT(activity: Activity, adContainer: ViewGroup?, adConfig: ADConfigBean, adStyle: Int, layout: Int, adListener: BaseAdListener?) {
            //判断保底广告的位置是否为头条广告
            val positionId = when {
                TextUtils.equals(adConfig.second_ad_type, ADConfigBean.TYPE_TODAYNEWS.toString()) -> adConfig.second_ad_position_id
                TextUtils.equals(adConfig.third_ad_type, ADConfigBean.TYPE_TODAYNEWS.toString()) -> adConfig.third_ad_position_id
                else -> ""
            }
            if (TextUtils.isEmpty(positionId)) {
                AdUtils.fetchRenderAd(activity, adContainer, adConfig, adStyle, layout, adListener)
                return
            }
            adConfig.ad_position_id = positionId
            adConfig.ad_type = ADConfigBean.TYPE_TODAYNEWS.toString()
            Log.i("pVUVAd", "请求方式：${AdPresenter.AD_REQUEST}  广告商：保底广告-头条  广告位置：${adConfig.ad_position} 广告Id：$positionId")
            AdPresenter.pVUVAdStatics(AdPresenter.AD_REQUEST, adConfig.ad_type, adConfig.ad_position.toInt())
            when (adStyle) {
                AdStyleBean.BANNER_STYLE -> AdTouTiaoUtils.fetchNativeBannerAd(activity, adContainer, adConfig, adStyle, layout, adListener)
                else -> adListener?.onAdLoadFailed()
            }
        }

        //获取阅读器广告失败时调用(修改阅读器下方Banner保底广告(头条+广电通))
        fun fetchAdFailed(activity: Activity, adContainer: ViewGroup?, adConfig: ADConfigBean, adStyle: Int, layout: Int, adListener: BaseAdListener?) {
            //修改阅读器下方Banner保底广告(头条+广电通)
            when (adConfig.ad_position?.toInt()) {
                ADConfigBean.POSITION_BOOK_READER_BOTTOM, ADConfigBean.POSITION_BOOK_READER_BOTTOM_5 ->
                    AdUtils.fetchRenderAdByTT(activity, adContainer, adConfig, adStyle, layout, adListener)
                else -> AdUtils.fetchRenderAd(activity, adContainer, adConfig, adStyle, layout, adListener)
            }
        }

        @JvmStatic
        fun destroyAd(adContainer: ViewGroup?) {
            adContainer?.run {
                val tag = tag ?: return
                removeAllViews()
                when (tag) {
                    is InMobiNative -> tag.destroy()
                    is NativeExpressADView -> tag.destroy()
                    is BannerView -> tag.destroy()
                    is TorchNativeAdLoader -> tag.destroy()
                    is CenBanner -> tag.onDestory(context)
                }
                LuoMiUtils.onDestroyAd(context)
            }
        }

        /**
         *广告上报统计
         */
        fun pVUVAd(requestType: String, adConfig: ADConfigBean) {
            Log.i("pVUVAd", "请求方式：$requestType   广告类型： ${adConfig.ad_type}  广告商：${ADConfigBean.getAdName(adConfig.ad_type)}  广告位置：${adConfig.ad_position}  广告Id：${adConfig.ad_position_id}")
            AdPresenter.pVUVAdStatics(requestType, adConfig.ad_type, adConfig.ad_position.toInt())
            if (requestType == AdPresenter.AD_REQUEST) {
                //请求广告就算一次有效次数
                addAdTime(adConfig)
            }
        }

        /**
         * @param activity      展示广告的activity
         * @param adContainer   展示广告的大容器
         * @param skipContainer 自定义的跳过按钮
         * @param position      广告位置
         * @param adListener    广告状态监听器
         */

        @JvmStatic
        fun fetchAdUtil(activity: Activity, adContainer: ViewGroup?, skipContainer: TextView?, position: Int, adStyle: Int, layout: Int, adListener: BaseAdListener?): Boolean {
            val config = ADConfigs.showAD(position.toString())
            if (config == null) {
                adListener?.onAdLoadFailed()
                return false
            }
            var b = false
            if (Utils.isEmptyList(config.ad_type_lists)) {
                adListener?.onAdLoadFailed()
                return false
            } else {
                for (i in config.ad_type_lists.indices) {
                    val time = AdExploreTimeUtils.getAdExposureTime(config.ad_type_lists[i]?.ad_position, config.ad_type_lists[i]?.ad_type)
                    //Log.i("evan", "time:$time  exposure:${config.ad_type_lists[i].exposure}  type:${config.ad_type_lists[i].ad_type}  ad_position:${config.ad_type_lists[i].ad_position}")
                    val exposure = config.ad_type_lists[i]?.exposure?.toIntOrNull() ?: 0
                    //后台曝光数据全未0时，则推出广告循环
                    if (exposure == 0) {
                        b = false
                        continue
                    }
                    b = true
                    if (time > exposure - 1) {
                        continue
                    }
                    Log.i("evan", "未到曝光次数，获取广告数据")
                    config.ad_position = config.ad_type_lists[i]?.ad_position?.trim()
                    config.ad_type = config.ad_type_lists[i]?.ad_type?.trim()
                    if (!TextUtils.isEmpty(config.ad_type_lists[i]?.ad_position_id)) {
                        config.ad_position_id = config.ad_type_lists[i]?.ad_position_id?.trim()
                    } else {
                        config.ad_position_id = ""
                    }
                    //拉取广告
                    return getAdData(activity, adContainer, skipContainer, config, adStyle, layout, adListener)
                }
                if (!b) {
                    adListener?.onAdLoadFailed()
                    resetLocalExposure(config)
                    return false
                }
                //重置曝光次数
                resetLocalExposure(config)
                //重新循环广告
                return fetchAdUtil(activity, adContainer, skipContainer, position, adStyle, layout, adListener)
            }
        }

        private fun addAdTime(adConfig: ADConfigBean) {
            var time = AdExploreTimeUtils.getAdExposureTime(adConfig.ad_position, adConfig.ad_type)
            time++
            //SettingManager.getInstance().saveAdExposureTime(adConfig.ad_position, adConfig.ad_type, time)
            AdExploreTimeUtils.saveAdExposureTime(adConfig.ad_position, adConfig.ad_type, time)
        }

        //点击当前广告商曝光满，切换下一个广告商
        fun addFullExposureTime(activity: Activity, adContainer: ViewGroup?, skipContainer: TextView?, position: Int, adStyle: Int, layout: Int, adListener: BaseAdListener?, curAdType: Int) {
            val config = ADConfigs.showAD(position.toString()) ?: return
            config.ad_type_lists.forEach {
                if (it.ad_type.toInt() == curAdType) {
                    //SettingManager.getInstance().saveAdExposureTime(it.ad_position, it.ad_type, it.exposure.toInt())
                    AdExploreTimeUtils.saveAdExposureTime(it.ad_position, it.ad_type, it.exposure.toInt())
                    fetchAdUtil(activity, adContainer, skipContainer, position, adStyle, layout, adListener)
                    return@forEach
                }
            }
        }

        private fun resetLocalExposure(config: ADConfigBean?) {
            //重置曝光次数
            config?.ad_type_lists?.forEach {
                //SettingManager.getInstance().saveAdExposureTime(it.ad_position, it.ad_type, 0)
                AdExploreTimeUtils.saveAdExposureTime(it.ad_position, it.ad_type, 0)
            }
        }
    }
}


fun getRootView(view: View): View {
    return if (view.parent != null) {
        getRootView(view.parent as View)
    } else {
        view
    }
}
